﻿using System;
using ASPItalia.ModelVirtualCasting.ObjectModel;
using System.ComponentModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ASPItalia.ModelVirtualCasting.Web.Models
{
    [Serializable]
    public class SearchModel
    {
        public string Nickname { get; set; }
        [DisplayName("Nome")]
        public string Firstname { get; set; }
        [DisplayName("Cognome")]
        public string Lastname { get; set; }
        [DisplayName("Da data nascita")]
        public DateTime? MinBirthDate { get; set; }
        [DisplayName("A data nascita")]
        public DateTime? MaxBirthDate { get; set; }

        [NonSerialized]
        private Country currentCountry;
        private int? countryId;

        [DisplayName("Residenza attuale")]
        public Country CurrentCountry
        {
            get { return this.currentCountry; }
            set { this.currentCountry = value; }
        }
        
        [DisplayName("Sesso")]
        public string Gender { get; set; }
        [DisplayName("Nudo")]
        public bool? Naked { get; set; }

        public string Serialize()
        {
            this.countryId = null;
            if (CurrentCountry != null)
                this.countryId = this.CurrentCountry.CountryID;

            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, this);
                ms.Position = 0;
                byte[] buffer = new byte[(int)ms.Length];

                ms.Read(buffer, 0, buffer.Length);

                return Convert.ToBase64String(buffer);
            }
        }

        public static SearchModel Deserialize(string value)
        {
            byte[] buffer = Convert.FromBase64String(value);

            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                var res = (SearchModel)formatter.Deserialize(ms);
                res.CurrentCountry = new Country();
                if (res.countryId.HasValue)
                    res.CurrentCountry.CountryID = res.countryId.Value;

                return res;
            }
        }
    }
}